<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-select v-model="queryParams.year" placeholder="选择年份" @change="handleYearChange">
          <el-option v-for="item in dict.type.biz_work_year_list" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.quarter" placeholder="选择季度" class="ml-10" @change="handleQuarterChange">
          <el-option v-for="item in quarterOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
        <el-select v-model="queryParams.deptId" placeholder="选择待审批站办所" class="ml-10" no-data-text="暂无待审批站办所" @change="getList">
          <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-col>
    </el-row>
    <div class="text-banner">
      <span>重点工作情况汇总（共 {{ keyWorkTotal }} 条）</span>
      <el-button size="mini" type="primary" circle icon="el-icon-refresh" plain @click="handleRefresh" />
    </div>
    <div v-loading="keyWorkLoading">
      <div class="float-right mb-10">
        <el-button
          size="mini"
          type="primary"
          plain
          icon="el-icon-menu"
          :disabled="!selectionList.length"
          v-hasPermi="['approval:key-supervision:pass']"
          @click="handleBatchApproval('pass')"
        >
          批量通过
        </el-button>
        <el-button
          size="mini"
          type="danger"
          plain
          icon="el-icon-menu"
          :disabled="!selectionList.length"
          v-hasPermi="['approval:key-supervision:reject']"
          @click="handleBatchApproval('reject')"
        >
          批量退回
        </el-button>
      </div>

      <el-table :data="keyWorkList" border style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column label="序号" type="index" align="center">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="normName" label="指标名称" width="180" align="center" show-overflow-tooltip> </el-table-column>
        <!-- <el-table-column prop="workNatureDict" label="工作性质" width="180" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.biz_work_nature" :value="scope.row.workNatureDict" />
          </template>
        </el-table-column> -->
        <el-table-column prop="month" label="月度" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.month }}月</span>
          </template>
        </el-table-column>
        <el-table-column prop="workContent" label="内容及方式" min-width="180" align="center">
          <template slot-scope="scope">
            <div class="pre-wrap align-left">{{ scope.row.workContent || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="planScore" label="分值" width="80" align="center"> </el-table-column>
        <el-table-column prop="workCompletionSituationDict" label="完成情况" min-width="120" align="center">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.biz_dept_important_work_completion" :value="scope.row.workCompletionSituationDict" />
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="150" align="center">
          <template slot-scope="scope">
            <span class="pre-wrap">{{ scope.row.remarks || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="selfScore" label="自评得分" width="80" align="center"></el-table-column>
        <el-table-column prop="workCompletionMaterialUrls" label="完成材料" min-width="180" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.workCompletionMaterialUrls">
              <el-tooltip
                v-for="(url, index) in scope.row.workCompletionMaterialUrls.split(',')"
                :key="index"
                effect="dark"
                :content="formatFileUrl(url)['name']"
                placement="top-start"
              >
                <el-button type="text" @click="handlePreviewFile(url)" class="file-preview-btn">
                  {{ formatFileUrl(url)['name'] }}
                </el-button>
              </el-tooltip>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="workCompletionDate" label="完成日期" width="160" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="140" fixed="right">
          <template slot-scope="scope">
            <ApprovalLog
              :biz-id="scope.row.workScoreId"
              v-hasPermi="['approval:key-supervision:pass']"
              v-show="checkBtnVisible('pass', scope.row.reportAuditStatusDict)"
            >
              <el-button type="text" size="mini" @click.stop="handleApproval(scope.$index, scope.row, 'pass')"> 通过 </el-button>
            </ApprovalLog>
            <ApprovalLog
              :biz-id="scope.row.workScoreId"
              v-hasPermi="['approval:key-supervision:reject']"
              v-show="checkBtnVisible('reject', scope.row.reportAuditStatusDict)"
            >
              <el-button type="text" size="mini" class="color-danger ml-10" @click.stop="handleApproval(scope.$index, scope.row, 'reject')">
                退回
              </el-button>
            </ApprovalLog>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <FilePreview :visible.sync="filePreviewVisible" :file="previewFile"></FilePreview>
  </div>
</template>

<script>
import { list as listPlan, approval, listDept } from '@/api/work-approval/dept-supervision'
import { quarterFormat } from '@/utils/quarter.js'
import FilePreview from '@/components/FilePreview'
import { mixins } from '@/mixins'
import ApprovalLog from '@/components/ApprovalLog'

export default {
  name: 'key-supervision-approval',
  mixins: [mixins],
  dicts: [
    'biz_work_year_list',
    'biz_work_nature',
    'biz_work_type',
    'biz_work_score_type',
    'biz_work_completion_stage',
    'biz_dept_important_work_completion'
  ],
  props: {},
  components: { FilePreview, ApprovalLog },
  data() {
    return {
      previewFile: {},
      filePreviewVisible: false,
      keyWorkTotal: 0,
      keyWorkList: [],
      keyWorkLoading: false,
      quarterOptions: [],
      deptCivilList: [],
      queryParams: {
        year: '',
        quarter: '',
        deptId: undefined,
        workType: 'ZDGZ'
      },
      selectionList: [],
      deptOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleYearChange(new Date().getFullYear())
  },
  methods: {
    // 表格多选
    handleSelectionChange(selection) {
      this.selectionList = selection
    },
    handleRefresh() {
      this.getDeptList()
    },
    // 获取待审批部门
    getDeptList() {
      let params = JSON.parse(JSON.stringify(this.queryParams))
      delete params.deptId
      listDept(params).then(res => {
        let { data } = res
        if (Array.isArray(data) && data.length) {
          this.deptOptions = res.data.map(item => {
            return { label: item.deptName, value: item.deptId }
          })
          let findDept = this.deptOptions.find(item => item.value === this.queryParams.deptId)
          if (!findDept) {
            this.queryParams.deptId = this.deptOptions[0].value
          }
        } else {
          this.deptOptions = []
          this.queryParams.deptId = ''
        }
        this.getList()
      })
    },
    // 校验表格是否可选
    checkSelectable(raw, index) {
      if (raw.supervisionAuditStatusDict === 'DSH') {
        return true
      }
      return false
    },

    // 批量审批
    handleBatchApproval(operation) {
      let auditRemark = '同意'
      let auditStatusDict = 'SHTG'
      if (operation === 'reject') {
        auditRemark = '不同意'
        auditStatusDict = 'SHBTG'
      }
      let params = this.selectionList.map(item => {
        return { id: item.id, auditRemark, auditStatusDict }
      })
      let content = `您正在审批已选中的 ${this.selectionList.length} 项工作，请输入审批意见`
      this.approvalPrompt(operation, content, auditRemark, params)
    },

    // 审批操作
    handleApproval(index, raw, operation) {
      let params = { id: raw.id, auditStatusDict: 'SHTG', auditRemark: '同意' }
      if (operation === 'reject') {
        params.auditStatusDict = 'SHBTG'
        params.auditRemark = '不同意'
      }
      let content = `您正在审批第 【${index + 1}】 项工作，请输入审批意见`
      this.approvalPrompt(operation, content, params.auditRemark, [params])
    },
    // 审批窗口
    approvalPrompt(operation, content, inputValue, params) {
      this.$prompt(content, '审批提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder: '输入审批意见',
        inputType: 'textarea',
        inputPattern: /\S/,
        inputValue: inputValue,
        inputErrorMessage: '审批意见不能为空',
        beforeClose: (action, instance, done) => {
          params.forEach(item => {
            item.auditRemark = instance.inputValue
          })
          if (action === 'confirm') {
            const loading = this.$loading({
              target: '.el-message-box',
              lock: true,
              text: '数据处理中',
              spinner: 'el-icon-loading',
              background: 'rgba(255,255,255,0.6)'
            })
            approval(params)
              .then(() => {
                loading.close()
                if (operation === 'pass') {
                  this.$modal.msgSuccess('已通过')
                } else if (operation === 'reject') {
                  this.$modal.msgError('已退回')
                }
                this.handleRefresh()
                done()
              })
              .catch(() => {
                loading.close()
                done()
              })
          } else {
            done()
          }
        }
      })
    },
    // 审核提示内容格式输出
    aduitContentFormat(raw) {
      let content = []
      content.push(`<p>审核意见：${raw.supervisionAuditRemark || ' - '}</p>`)
      content.push(`<p>审核时间：${raw.supervisionAuditTime || ' - '}</p>`)
      return content.join('')
    },
    // 功能类型、审核状态、提交状态
    checkBtnVisible(type, audit) {
      switch (type) {
        case 'pass': // 通过
        case 'reject': // 退回
          return audit === 'DSH'
        case 'finish': // 审核已完成
          return audit === 'SHTG'
        case 'returned': // 审核已完成
          return audit === 'SHBTG'
        default:
          return false
      }
    },
    // 预览文件
    handlePreviewFile(url) {
      let fileItem = this.formatFileUrl(url)
      this.previewFile = { url, ...fileItem }
      console.log('previewFile', this.previewFile)
      this.filePreviewVisible = true
    },
    // 年度选择
    handleYearChange(year) {
      this.queryParams.year = year
      // 获取当前季度、季度列表（往年默认第一季度）
      let { quarter, quarterList } = quarterFormat(year)
      this.quarterOptions = quarterList
      this.handleQuarterChange(quarter)
    },
    // 季度选择
    handleQuarterChange(quarter) {
      this.queryParams.quarter = quarter
      this.handleRefresh()
    },
    getList() {
      this.keyWorkLoading = true
      listPlan(this.queryParams)
        .then(res => {
          this.keyWorkLoading = false
          let { data } = res
          this.keyWorkTotal = data.length
          this.keyWorkList = data
        })
        .catch(err => (this.keyWorkLoading = false))
    }
  }
}
</script>

<style lang="scss" scoped>
.file-preview-btn {
  width: 100%;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  margin-left: 0;
  padding: 0;
}

::v-deep .el-input-number--medium {
  width: auto;
}
</style>
